package cn.edu.lit.myexpress;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ScrollingView;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

import cn.edu.lit.myexpress.gson.exp.ExpinfoList;
import cn.edu.lit.myexpress.gson.exp.Logistics;
import cn.edu.lit.myexpress.util.HttpUtil;
import cn.edu.lit.myexpress.util.Utility;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ExpressionActivity extends AppCompatActivity {

    private SwipeRefreshLayout swipeRefresh;
    private String expressNO;
    public DrawerLayout drawerLayout;
    private EditText et_courier_number;
    private Button btn_submit;
    private LinearLayout forecastLayout;
    private ScrollView logistics_scrollView;
    private String courierNumber;
    private String expressName;
    private Button nav_btn;
    private void init() {
        logistics_scrollView = findViewById(R.id.logistics_forecast);
        drawerLayout = findViewById(R.id.drawer_layout);
        nav_btn = findViewById(R.id.nav_button);
        et_courier_number = findViewById(R.id.et_courier_number);
        btn_submit = findViewById(R.id.bt_submit);
        forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_expression);
        init();
        logistics_scrollView.setVisibility(View.INVISIBLE);
        Intent it = getIntent();
        expressName=it.getStringExtra("expcName");
        expressNO = it.getStringExtra("expcNo");
        Toast.makeText(this,"快递公司编号："+expressNO,Toast.LENGTH_SHORT).show();

        nav_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                courierNumber = String.valueOf(et_courier_number.getText());
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ExpressionActivity.this);
                String logisticsinfo = prefs.getString(courierNumber, null);

                if(logisticsinfo!=null){//数据库中有数据
                Logistics logistics= Utility.handleLogisticResponse(logisticsinfo);
                showLogisticsInfo(logistics);
                }else {
                    Toast.makeText(ExpressionActivity.this,"订单编号："+courierNumber,Toast.LENGTH_SHORT).show();
                    queryLogisticsFromServer(expressNO,courierNumber);
                }

            }
        });
    swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            queryLogisticsFromServer(expressNO,courierNumber);
            Toast.makeText(ExpressionActivity.this,"更新成功！",Toast.LENGTH_SHORT).show();
            }
    });

    }


    public void queryLogisticsFromServer(String NO,String courierNo){
        String str= "http://v.juhe.cn/exp/index?com=%s&no=%s&senderPhone=&receiverPhone=&dtype=&key=4f4230575f8f0b66669fc56a2e0a803b";
        String address=String.format(str,NO,courierNo);
        HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(ExpressionActivity.this,"抱歉查询失败！",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final  String responseText = response.body().string();
                final Logistics logistics = Utility.handleLogisticResponse(responseText);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(logistics!=null){
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(ExpressionActivity.this).edit();
                            editor.putString(courierNumber,responseText);
                            editor.apply();
                            showLogisticsInfo(logistics);
                        }else {
                            Toast.makeText(ExpressionActivity.this,"获取信息失败！",Toast.LENGTH_SHORT).show();
                            swipeRefresh.setRefreshing(false);
                        }


                    }
                });
            }
        });
    }

    public void showLogisticsInfo(Logistics logistics){
        if (logistics.getResuultCode().equals("200")){
            forecastLayout.removeAllViews();
            for( ExpinfoList expinfoList:logistics.expinfoLists){
                View view = LayoutInflater.from(this).inflate(R.layout.forecast_item,forecastLayout,false);
                TextView dateText = view.findViewById(R.id.date_text);
                TextView  remarkText = view.findViewById(R.id.remark_text);
                dateText.setText(expinfoList.getDatetime());
                remarkText.setText(expinfoList.getRemark());
                forecastLayout.addView(view);
                swipeRefresh.setRefreshing(false);
                logistics_scrollView.setVisibility(View.VISIBLE);//设置为物流信息可见
            }
        }else {
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item,forecastLayout,false);
            TextView dateText = view.findViewById(R.id.date_text);
            dateText.setText(logistics.getReson());
            forecastLayout.addView(view);
            swipeRefresh.setRefreshing(false);
        }
    }

}
